﻿using Carer.Crm.Authorize;
using Carer.Crm.Services;
using Carer.Crm.ViewModel;
using Carer.Data;
using Carer.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Carer.Crm.Controllers
{
    public class HomeController : BaseController
    {

        [SessionAuthorize]
        public ActionResult Index()
        {
            ViewBag.Title = System.Configuration.ConfigurationManager.AppSettings["HomeTitle"] + "";

            return base.ViewModel();
        }

        [AllowAnonymous]
        public ActionResult Login()
        {
            return base.View();
        }

        [AllowAnonymous]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            base.Session.Clear();
            return base.RedirectToAction("Login", "Home");
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                #region 登录校验
                //var user = DataService.CheckUser(model.UserName, model.Password);
                var user = ServiceFactory.UserService.CheckUser(model.UserName, model.Password);
                if (user != null)
                {
                    Session["UserId"] = user.Id;
                    Session["UserInfo"] = user;
                    Session["UserUnit"] = user.Unit;

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
                        (1,
                            model.UserName,
                            DateTime.Now,
                            DateTime.Now.AddMinutes(20),
                            true,
                            "7,1,8",
                            "/"
                        );
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                    cookie.HttpOnly = true;
                    HttpContext.Response.Cookies.Add(cookie);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return base.Redirect(returnUrl);
                    }
                    else
                    {
                        return base.RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名或密码错误。");
                    return View(model);
                }
                #endregion
            }
            else
            {
                return View(model);
            }
        }

        [SessionAuthorize]
        public ActionResult SwitchUnit(int id)
        {
            if (id > 0)
            {
                base.Session["UserUnit"] = DataService.GetUnit(id);
            }
            return base.RedirectToAction("Index", "Home");
        }


        [SessionAuthorize]
        [HttpGet]
        public JsonResult GetConfig()
        {
            try
            {
                int? unitId = this.GetUserUnitId();
                #region 多线程方式
                ////服务类别(护工、月嫂)
                //Task<List<SelectListItem>> task1 = Task.Factory.StartNew(() =>
                //{
                //    var userCategories = DataService.GetAllCategories(unitId);
                //    return userCategories.Select(it => new SelectListItem() { Text = it.Name, Value = it.Name, Selected = false }).ToList();
                //});

                ////人员性质(加盟、外包)
                //Task<List<SelectListItem>> task2 = Task.Factory.StartNew(() =>
                //{
                //    var crewTypes = DataService.GetAllCrewTypes(unitId);
                //    return crewTypes.Select(it => new SelectListItem() { Text = it.Name, Value = it.Name, Selected = false }).ToList();
                //});

                ////结算标准
                //Task<List<SelectListItem>> task3 = Task.Factory.StartNew(() =>
                //{
                //    var payments = DataService.GetAllPayments(unitId);
                //    return payments.Select(it => new SelectListItem() { Text = it.Name, Value = it.Id.ToString(), Selected = false }).ToList();
                //});
                ////所有单位
                //Task<List<SelectListItem>> task4 = Task.Factory.StartNew(() =>
                //{
                //    var units = DataService.GetAllUnits();
                //    return units.Select(it => new SelectListItem() { Text = it.Name, Value = it.Id.ToString(), Selected = false }).ToList();
                //});
                //Task.WaitAll(task1, task2, task3, task4);
                //return new JsonResult()
                //{
                //    Data = new HttpRspDTO()
                //    {
                //        Success = true,
                //        Data = new
                //        {
                //            ServiceType = task1.Result,
                //            CrewType = task2.Result,
                //            Payment = task3.Result,
                //            UserUint = this.GetUserUnit(),
                //            AllUnit = task4.Result
                //        }
                //    },
                //    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                //};
                #endregion

                //服务类别(护工、月嫂)
                var userCategories = ServiceFactory.CategoryService.GetAllCategories(unitId);
                List<SelectListItem> serviceType = userCategories.Select(it => new SelectListItem() { Text = it.Name, Value = it.Name, Selected = false }).ToList();

                //人员性质(加盟、外包)              
                var crewTypes = ServiceFactory.CrewTypeService.GetAllCrewTypes(unitId);
                List<SelectListItem> crewType = crewTypes.Select(it => new SelectListItem() { Text = it.Name, Value = it.Name, Selected = false }).ToList();


                //结算标准
                var payments = ServiceFactory.PaymentService.GetAllPayments(unitId);
                List<SelectListItem> payment = payments.Select(it => new SelectListItem() { Text = it.Name, Value = it.Id.ToString(), Selected = false }).ToList();

                //所有单位
                var units = ServiceFactory.UnitService.GetAllUnits();
                List<SelectListItem> allUnit = units.Select(it => new SelectListItem() { Text = it.Name, Value = it.Id.ToString(), Selected = false }).ToList();


                return new JsonResult()
                {
                    Data = new HttpRspDTO()
                    {
                        Success = true,
                        Data = new
                        {
                            ServiceType = serviceType,
                            CrewType = crewType,
                            Payment = payment,
                            UserUint = this.GetUserUnit(),
                            AllUnit = allUnit
                        }
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            catch (Exception ex)
            {
                return new JsonResult()
                {
                    Data = new HttpRspDTO()
                    {
                        Success = false,
                        Message = ex.Message
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }

        }
    }
}
